<?php


namespace app\model;

use fast\Http;
use think\api\Client;
use think\facade\Log;
use think\Model;

/**
 * 抓拍记录
 */
class Faces extends Model {

    public function saev_face($content){
        $content=json_decode($content,true);
        $faces=$content['FaceListObject']['FaceObject'];
        foreach ($faces as $face) {
            //Log::info("推送人像：".json_encode($face));
            //$path=config('capture_path').$face['DeviceID'].'/';
            $path=config('capture.capture_path').'/'.$face['DeviceID'].'/'.date('Ym').'/'.date('d').'/';
            $images=$face['SubImageList']['SubImageInfoObject'];
            $data['device_id']=$face['DeviceID'];
            $device=ViidDevice::where('device_id','=',$data['device_id'])->find();
            if($device){
                $aizone=Aizone::find($device['aizone_id']);
                $data['device_name']=$device['name'];
                $data['aizone_id']=$device['aizone_id'];
                $data['aizone_name']=$device['aizone_name'];
                $data['address_id']=$aizone['name_code'];
                $data['dwid']=$device['dwid'];
            }
            $data['face_id']=$face['FaceID'];
            $data['source_id']=$face['SourceID'];
            $data['img_bg']=$images[0]['ImageID'];
            $data['img_face']=$images[1]['ImageID'];
            $data['file_path']=$path;
            try {
                $this->save($data);
                $data['id']=$this->id;
                //调
                $data['longitude']=$device['longitude'];
                $data['latitude']=$device['latitude'];
                Http::post('http://127.0.0.1:9503',['content'=>json_encode($data)]);
            }catch (\Exception $e){
                Log::info("保存错误：".$e->getMessage());
            }
            Log::info("保存face:".json_encode($this->toArray()));
            save_base_img($this->id.'_bg',$images[0]['Data'],$path);
            save_base_img($this->id.'_face',$images[1]['Data'],$path);
            ViidDevice::where('device_id',$device['device_id'])->save(['last_time'=>date('Y-m-d H:i:s')]);
             // 比对服务器没有确定 暂时只保存图 不比对
            // $single_data=$this->compare('data: image/png;base64,'.$images[1]['Data'],$data);
            // if(isset($single_data['photo_id'])){
            //     Log::info("face更新：");
            //     $data['photo_id'] = $single_data['photo_id'];
            //     $data['album_id'] = $single_data['album_id'];
            //     $data['scores'] = $single_data['score'];
            //     $this->save($data);
            // }

            // $info=MqttFacePushInfo::insert_compare_result(array_merge($single_data,$this->toArray()));
            
            //布控
            if($single_data['photo_id']) {
                $tasks = Task::getAvaTask($device['id']);
                if ($tasks) {
                    foreach ($tasks as $task) {
                        $res = $this->compare_by_album_ids('image/jpeg;base64,'.$images[1]['Data'], [$task['album_id']]);
                        if ($res) {
                            $task['push_id']=$info->id;
                            $task['photo_id']=$res['photo_id'];
                            $task['queue']=1;
                            $task['find_device_id']=$face['DeviceID'];
                            $task['dongjian_result']=json_encode($res);
                            Task::finishTask($task,1);
                        }
                    }

                }
            }
        }
    }

    public function compare_by_face_id($id){
        $data=$this->find($id);
        $res=$this->compare(base64_img($data['file_path']));
        $res=json_decode($res,true);
        if($res['code']===0){
            $datas=$res['data']['results'];
            if(count($datas)>0){
                $single_data=$datas[0];
                MqttFacePushInfo::insert_compare_result(array_merge($single_data,$data->toArray()));
            }
        }
        return null;
    }

    /**
     * 比较底库
     * 先比较实名库，再比较未实名库，如果都没有，则放入未实名库
     * @param $photo
     * @return mixed
     */
    public function compare($photo,$data){
        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        //实名库比较
        $res=json_decode($service->compare_face($photo,1),true);
        Log::info("实名库比较结果：".json_encode($res));
        if($res&&$res['code']===0){
            $datas=$res['data']['results'];
            if(count($datas)>0){
                return $datas[0];
            }else{
                //未实名库比较
                $res=json_decode($service->compare_face($photo,2),true);
                if($res['code']===0) {
                    $datas = $res['data']['results'];
                    if (count($datas) > 0) {
                        return $datas[0];
                    } else {
                        if(!$data){
                            return [];
                        }else{
                            //创建人员放入未实名库
                            $face = new MqttUserManage();
                            $face->photo=$photo;
                            $face->ywlsh=$data['face_id'];
                            $face->name='';
                            $face->address=$data['aizone_name'];
                            $face->phone='';
                            $post_ai_return=$service->create_face($face,2);
                            /*$post_ai_return_array=json_decode($post_ai_return,true);
                            $photo_id=0;
                            if($post_ai_return_array['code']===0){
                                $res=$post_ai_return_array['data'];
                                $data['photo_id']=$res['photo_id'];
                                $data['album_id']=$res['album_id'];
                                $data['']
                            }*/
                            //$res=$service->compare_face($photo,2);
                            /*if($res['code']===0) {
                                $datas = $res['data']['results'];
                                if (count($datas) > 0) {
                                    return $datas[0];
                                } else {
                                    $post_ai_return_array = json_decode($post_ai_return, true);
                                    if ($post_ai_return_array['code'] === 0) {
                                        $res = $post_ai_return_array['data'];
                                        $data['photo_id'] = $res['photo_id'];
                                        $data['album_id'] = $res['album_id'];
                                        return $data;
                                    }
                                }
                            }*/
                            Log::info("洞签新增人物：".$post_ai_return);
                            $post_ai_return_array = json_decode($post_ai_return, true);

                            if ($post_ai_return_array['code'] === 0) {
                                $res = $post_ai_return_array['data'];
                                return $res;
                            }
                        }

                    }
                }
            }
        }
        return [];
    }

    public function compare_by_album_ids($photo, $album_ids) {
        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        //实名库比较
        $res=$service->compare_face($photo,$album_ids);
        $res=json_decode($res,true);
        if($res['code']===0) {
            $datas = $res['data']['results'];
            if (count($datas) > 0) {
                return $datas[0];
            }
        }
        return 0;
    }

    public function compare_photo($photo,$start_time,$end_time) {
        $service_type=config('capture.platform');
        $service=null;
        eval('$service= new app\service\impl\Albums'.$service_type.'ServiceImpl();');
        //实名库比较
        $albums=Albums::where(['is_neijiang'=>1])->column('album_id');
        if($albums){
            $res=$service->compare_face($photo,$albums,$start_time,$end_time);
            $res=json_decode($res,true);
            if($res['code']===0) {
                return $res['data']['results'];
            }
        }
        return [];
    }
}